package com.yy.util.common;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.util.Log;

/**
 * 检查网络链接工具类
 * @author zhangLy
 *
 */
public class NetUtils {
	
	private final static String TAG = NetUtils.class.getSimpleName();

	/**
	 * 检查网络状态
	 * @param context
	 * @return
	 */
	public static boolean checkNet(Context context) {
		boolean isWifi = isNetConnection(context,
				ConnectivityManager.TYPE_WIFI);
		boolean isMobile = isNetConnection(context,
				ConnectivityManager.TYPE_MOBILE);

		if (isMobile) {
			Log.i(TAG, "--->>> Now use Mobile net");
			//readAPN(context);
		}
		if (!isWifi && !isMobile) {
			Log.i(TAG, "--->>> not net!!!");
			return false;
		}
		return true;
	}

	/**
	 * 读取手机apn信息
	 * @param context
	 */
	@SuppressWarnings("unused")
	private static void readAPN(Context context) {
		Uri uri = Uri.parse("content://telephony/carriers/preferapn");
		ContentResolver resolver = context.getContentResolver();
		Cursor cursor = resolver.query(uri, null, null, null, null);
		if(cursor != null && cursor.moveToFirst()) {
			String proxy = cursor.getString(cursor.getColumnIndex("proxy"));
			int port = cursor.getInt(cursor.getColumnIndex("port"));
		}
	}

	/**
	 * 检查网络连接是否正常
	 * @param context
	 * @param netType
	 * @return
	 */
	private static boolean isNetConnection(Context context, int netType) {
		ConnectivityManager manager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = null;
		switch (netType) {
		case ConnectivityManager.TYPE_WIFI:
			info = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
			break;
		case ConnectivityManager.TYPE_MOBILE:
			info = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
			break;
		}
		if (info != null) {
			return info.isConnected();
		}
		return false;
	}
}
